﻿using Glorysoft.Auto.Xfw;
using Glorysoft.Auto.Xfw.Entities;
using Glorysoft.EAP.Core;
using Newtonsoft.Json;
using Glorysoft.EAP.Core.Enums;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Glorysoft.EAP.Core.Entities;
using FluentFTP.Helpers;

namespace Glorysoft.EAP.RC.EAPClient
{
    /// <summary>
    /// EAP调用EAPClient接口可以支持http，rabbitmq,nats mq
    /// </summary>
    public class EAPClientService : AbstractService
    {
        private readonly Logger CimLogger;
        public readonly string EAPServer = Dict.Current.EAPName;// "EAPServer";
        public string RMSError = "EAPClient time out.";
        public const string SendLotStatus = "SendLotStatus";
        public const string RemoveLotInfo = "RemoveLotInfo";
        public const string SendWaferStatus = "SendWaferStatus";
        private DbService dbServer = null;

        public EAPClientService()
        {
            try
            {
                
                CimLogger = XfwContext.LogManager.EapLogger;
                dbServer = new DbService();
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.EAPClientService() Execute Error.");
            }
        }
        public string Name => GetType().Name;
        public string CurrentMethod => MethodBase.GetCurrentMethod().Name;


        public void ShowAlarm(string message)
        {
            string eqpID = Dict.Current.OCRName;
            MessageOrigin messageOrigin = MessageOrigin.OCR;
            if (string.IsNullOrEmpty(eqpID))
            {
                eqpID = Dict.Current.DaemonName;
            }
            var headername = "ShowAlarmMessage";
            if (message == null)
            {
                CimLogger.Warning($"{Name}.ShowMessage() Execute, message==null|| message.Count==0.");
                return;
            }
            var msg = new Dictionary<string, string>();
            msg.Add("CN", message);
            msg.Add("EN", message);
            var request = new Publish() { Header = XfwUtils.CreateHeader(headername, EAPServer) };
            request.Body.AddString(CItems.EqpID, eqpID);
            request.Body.AddString(CItems.MessageType, MessageType.Alarm.ToString());
            request.Body.AddObject(CItems.TerminalMessage, msg);
            request.Body.AddString(CItems.MessageOrigin, messageOrigin.ToString());

            var ctx = XfwContext.GetMqContextByEAP(EAPServer);
            var strText = XfwUtils.Serialization(request.GetSerializationObject());
            ctx.Publish(strText);
        }
        #region 用户登录
        public void Login(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                xfwArgs.Header[CItems.UserName] = body.GetVal(CItems.UserName);
                xfwArgs.Header[CItems.PassWord] = body.GetVal(CItems.PassWord);
                xfwArgs.Header[CItems.FacilityId] = body.GetVal(CItems.FacilityId);
                CimLogger.Information($"{Name}.Login() UserName:{ xfwArgs.Header[CItems.UserName]?.ToString()} ,PassWord:{xfwArgs.Header[CItems.PassWord?.ToString()]} ,FacilityId{  xfwArgs.Header[CItems.FacilityId?.ToString()]}.");
                xfwArgs.SetReturnCodeOK();
                dbServer.InsertMsgInfo($"用户：{body.GetVal(CItems.UserName)}请求登录信息", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.Login() Execute Error.");
            }
        }
        public void LoginReply(XfwArgs xfwArgs)
        {
            try
            {
                var body = xfwArgs.Header[CItems.Response]?.ToString();
                // var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                //res.Body = json;
                res.Return = new Return { ReturnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString(), ReturnMessage = xfwArgs.Header[CItems.ReturnMessage]?.ToString() };

                //xfwArgs.Header[CItems.ReturnCode] = json.GetVal("RCode");
                //xfwArgs.Header[CItems.ReturnMessage] = json.GetVal("RMsg");
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                CimLogger.Information($"{Name}.LoginReply() ReturnCode:{ xfwArgs.Header[CItems.ReturnCode]?.ToString()} \n ReturnMessage:{xfwArgs.Header[CItems.ReturnMessage]?.ToString()}");
                xfwArgs.SetReturnCodeOK();
                var results = xfwArgs.Header[CItems.ReturnCode]?.ToString() == "OK" ? "成功" : "失败";
                dbServer.InsertMsgInfo($"用户：{ Dict.Current.lotInfo.userName}登录{results}", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);

            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.DownloadProgramReply() Execute Error.");
            }
        }
        #endregion

        #region 获取批次信息
        public void GetCarrierLotInfo(XfwArgs xfwArgs)
        {
            try
            {           
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                xfwArgs.Header[CItems.EqpID] = eqpID;
                xfwArgs.Header[CItems.LotID] = body.GetVal(CItems.LotID);
                xfwArgs.Header[CItems.UserName] = body.GetVal(CItems.UserName);
                xfwArgs.Header[CItems.FacilityId] = body.GetVal(CItems.FacilityId);
                xfwArgs.Header[CItems.ProberCardId] = body.GetVal(CItems.ProberCardId);
                Dict.Current.lotInfo.Alignment = body.GetVal(CItems.Alignment);
                Dict.Current.lotInfo.TestMode = body.GetVal(CItems.TestMode);
                Dict.Current.lotInfo.facilityId = xfwArgs.Header[CItems.FacilityId]?.ToString();
                Dict.Current.lotInfo.ProberCardId = body.GetVal(CItems.ProberCardId);
                xfwArgs.SetReturnCodeOK();
                CimLogger.Information($"{Name}.GetCarrierLotInfo() EqpID:{eqpID},LotID:{ xfwArgs.Header[CItems.LotID]?.ToString()},ProberCardId:{Dict.Current.lotInfo.ProberCardId}");
                dbServer.InsertMsgInfo($"获取批次信息", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);

            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.GetCarrierLotInfo() Execute Error.");
            }
        }
        public void GetCarrierLotInfoReply(XfwArgs xfwArgs)
        {
            try
            {
                //   var body = xfwArgs.Header[CItems.Response]?.ToString();
                //   var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Body.Add(CItems.UserName, xfwArgs.Header[CItems.UserName]?.ToString());
                res.Body.Add(CItems.WaferQty, xfwArgs.Header[CItems.WaferQty]?.ToString());
                res.Body.Add(CItems.lotStatus, xfwArgs.Header[CItems.lotStatus]?.ToString());
                res.Body.Add(CItems.productId, xfwArgs.Header[CItems.productId]?.ToString());
                res.Body.Add(CItems.LotID, xfwArgs.Header[CItems.LotID]?.ToString());
                res.Body.Add(CItems.ProberRecipe, xfwArgs.Header[CItems.ProberRecipe]?.ToString());
                res.Body.Add(CItems.stageId, xfwArgs.Header[CItems.stageId]?.ToString());
                res.Body.Add(CItems.Priority, xfwArgs.Header[CItems.Priority]?.ToString());
                // ADD ProcessId
                res.Body.Add(CItems.ProcessId, xfwArgs.Header[CItems.ProcessId]?.ToString());
                res.Body.Add(CItems.TestProgram, xfwArgs.Header[CItems.TestProgram]?.ToString());
                res.Body.Add(CItems.CustomerLotId, xfwArgs.Header[CItems.CustomerLotId]?.ToString());
                res.Body.Add(CItems.rcflag, xfwArgs.Header[CItems.rcflag]?.ToString());
                //var units = new  List<unitsInfo>();
                //foreach(var unit in xfwArgs.Header[CItems.UnitList])
                //{
                //    units.Add(unit);
                //}
                //  var AAA = xfwArgs.Header[CItems.UnitList] as List<unitsInfo>;
                //  var BB = JsonConvert.SerializeObject(AAA);
                res.Body.Add(CItems.UnitList, xfwArgs.Header[CItems.UnitList]?.ToString());
                res.Body.Add(CItems.SamplePrompts, xfwArgs.Header[CItems.SamplePrompts]?.ToString());
                res.Return = new Return { ReturnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString(), ReturnMessage = xfwArgs.GetReturnMessage() };

                //xfwArgs.Header[CItems.ReturnCode] = json.GetVal("RCode");
                //xfwArgs.Header[CItems.ReturnMessage] = json.GetVal("RMsg");
                xfwArgs.Header[CItems.ReturnCode] = res.Return.ReturnCode;
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                //xfwArgs.SetReturnCodeOK();
                CimLogger.Information($"{Name}.GetCarrierLotInfoReply() ReturnCode:{xfwArgs.Header[CItems.ReturnCode]?.ToString()}.");
                var results = xfwArgs.Header[CItems.ReturnCode]?.ToString() == "OK" ? "成功" : "失败";
                dbServer.InsertMsgInfo($"获取批次信息-{results}", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);


            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.GetCarrierLotInfoReply() Execute Error.");
            }
        }
        #endregion

        #region 验证批次信息，批次进站
        public void TrackIn(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                xfwArgs.Header[CItems.EqpID] = eqpID;
                xfwArgs.Header[CItems.FacilityId] = body.GetVal(CItems.Station);
                xfwArgs.Header[CItems.UserName] = body.GetVal(CItems.UserName);
                xfwArgs.Header[CItems.LotID] = body.GetVal(CItems.LotID);
                xfwArgs.Header[CItems.LotID] = body.GetVal(CItems.LotID);
                xfwArgs.Header[CItems.DatalogFile] = body.GetVal(CItems.DatalogFile);
                xfwArgs.Header[CItems.DatalogFilePath] = body.GetVal(CItems.DatalogFilePath);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SaveTest() Execute Error.");
            }
        }
        public void TrackInReply(XfwArgs xfwArgs)
        {
            try
            {
                var body = xfwArgs.Header[CItems.Response]?.ToString();
                var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Body = json;
                res.Return = new Return { ReturnCode = xfwArgs.GetReturnCode(), ReturnMessage = xfwArgs.GetReturnMessage() };

                xfwArgs.Header[CItems.ReturnCode] = json.GetVal("RCode");
                xfwArgs.Header[CItems.ReturnMessage] = json.GetVal("RMsg");
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.DownloadProgramReply() Execute Error.");
            }
        }
        #endregion

        #region 出站发送End Test
        public void TrackOut(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                xfwArgs.Header[CItems.EqpID] = eqpID;
                xfwArgs.Header[CItems.Station] = body.GetVal(CItems.Station);
                xfwArgs.Header[CItems.SummaryFile] = body.GetVal(CItems.SummaryFile);
                xfwArgs.Header[CItems.SummaryFilePath] = body.GetVal(CItems.SummaryFilePath);
                xfwArgs.Header[CItems.DatalogFile] = body.GetVal(CItems.DatalogFile);
                xfwArgs.Header[CItems.DatalogFilePath] = body.GetVal(CItems.DatalogFilePath);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SaveTest() Execute Error.");
            }
        }
        public void TrackOutReply(XfwArgs xfwArgs)
        {
            try
            {
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                if (string.IsNullOrEmpty(eqpID))
                {
                    eqpID = Dict.Current.TesterID;
                }
                var request = new Publish() { Header = XfwUtils.CreateHeader(RemoveLotInfo, EAPServer) };
                request.Body.AddString(CItems.EqpID, eqpID);

                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.DownloadProgramReply() Execute Error.");
            }
        }
        #endregion

        /// <summary>
        /// 心跳接口，判断是否断线
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void HearBeat(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);

                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                var ocrStatus = Dict.Current.OCRConnStatus;
                var rcmStatus = Dict.Current.RCMConnStatus;
                var ocrTesterStatus = Dict.Current.OCRTesterConnStatus;
                res.Body.Add(CItems.EqpID, eqpID);
                res.Body.Add(CItems.OCRConnStatus, ocrStatus);
                res.Body.Add(CItems.RCMConnStatus, rcmStatus);
                res.Body.Add(CItems.OCRTesterConnStatus, ocrTesterStatus);
                res.Return = new Return { ReturnCode = "OK", ReturnMessage = "conn" };
                xfwArgs.Header[CItems.ReturnCode] = res.Return.ReturnCode;
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();


            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.HearBeat() Execute Error.");
            }
            //Task.Factory.StartNew(() =>
            //{

            //});
        }

        /// <summary>
        /// 设备状态上报：
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void EqpStatusReport(XfwArgs xfwArgs)
        {
            try
            {
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                var status = xfwArgs.Header[CItems.EqpStatus]?.ToString();

                var request = new Publish() { Header = XfwUtils.CreateHeader("EqpStatusReport", EAPServer) };
                request.Body.AddString(XfwCItems.EqpID, eqpID);
                request.Body.AddString(XfwCItems.EqpStatus, status);
                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
                //if (res == null)
                //{
                //    XfwContext.EapLogger.Error($"EqpStatusReport Execute Error.");
                //    return;
                //}
                //var retMsg = res.GetReturnObject();
                CimLogger.Information($"EqpStatusReport() Execute. eqpID: {eqpID}, status: {status}");

                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.EqpStatusReport() Execute Error.");
            }
        }
        /// <summary>
        /// 设备状态上报
        /// </summary>
        /// <param name="eqpID"></param>
        /// <param name="eqpStatus"></param>
        public void EqpStatusReport(string eqpID, string eqpStatus)
        {
            try
            {
                var request = new Publish() { Header = XfwUtils.CreateHeader("EqpStatusReport", EAPServer) };
                request.Body.AddString(XfwCItems.EqpID, eqpID);
                request.Body.AddString(XfwCItems.EqpStatus, eqpStatus);
                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
                CimLogger.Information($"EqpStatusReport() Execute. eqpID: {eqpID}, eqpStatus: {eqpStatus}");

            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.EqpStatusReport(string eqpID,string eqpStatus) Execute Error.");
            }
        }

        /// <summary>
        /// log 日志上报
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void ShowMessage(XfwArgs xfwArgs)
        {
            try
            {
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                if (string.IsNullOrEmpty(eqpID))
                {
                    eqpID = Dict.Current.DaemonName;
                }
                var messageType = xfwArgs.Header[CItems.MessageType]?.ToString();
                var message = xfwArgs.Header[CItems.TerminalMessage] as Dictionary<string, string>;
                var messageOrigin = xfwArgs.Header[CItems.MessageOrigin]?.ToString();
                if (message == null || message.Count == 0)
                {
                    CimLogger.Warning($"{Name}.ShowMessage() Execute, message==null|| message.Count==0.");
                    return;
                }
                var request = new Publish() { Header = XfwUtils.CreateHeader("ShowMessage", EAPServer) };
                request.Body.AddString(CItems.EqpID, eqpID);
                request.Body.AddString(CItems.MessageType, messageType);
                request.Body.AddObject(CItems.TerminalMessage, message);
                request.Body.AddString(CItems.MessageOrigin, messageOrigin);

                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);

                //if (res == null)
                //{
                //    XfwContext.EapLogger.Error($"ShowMessage Execute Error.");
                //    return;
                //}
                //var retMsg = res.GetReturnObject();
                //  XfwContext.EapLogger.Information($"ShowMessage() Execute. ReturnCode: {retMsg.ReturnCode}, ReturnMessage: {retMsg.ReturnMessage}");
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.ShowMessage() Execute Error.");
            }
        }

        public void ShowMessage(string eqpID, MessageType messageType, Dictionary<string, string> message, MessageOrigin messageOrigin)
        {
            if (string.IsNullOrEmpty(eqpID))
            {
                eqpID = Dict.Current.DaemonName;
            }
            var headername = "ShowMessage";
            if (message == null || message.Count == 0)
            {
                CimLogger.Warning($"{Name}.ShowMessage() Execute, message==null|| message.Count==0.");
                return;
            }

            if (messageType == MessageType.Alarm && message.Count > 0)
            {
                headername = "ShowAlarmMessage";
            }
            var request = new Publish() { Header = XfwUtils.CreateHeader(headername, EAPServer) };
            request.Body.AddString(CItems.EqpID, eqpID);
            request.Body.AddString(CItems.MessageType, messageType.ToString());
            request.Body.AddObject(CItems.TerminalMessage, message);
            request.Body.AddString(CItems.MessageOrigin, messageOrigin.ToString());

            var ctx = XfwContext.GetMqContextByEAP(EAPServer);
            var strText = XfwUtils.Serialization(request.GetSerializationObject());
            ctx.Publish(strText);
        }


        public void ShowMessage(string message,params object?[] args)
        {
            string eqpID = Dict.Current.OCRName;
            MessageOrigin messageOrigin = MessageOrigin.OCR;
            if (string.IsNullOrEmpty(eqpID))
            {
                eqpID = Dict.Current.DaemonName;
            }
            var headername = "ShowMessage";
            if (message == null)
            {
                CimLogger.Warning($"{Name}.ShowMessage() Execute, message==null|| message.Count==0.");
                return;
            }
            var msg = new Dictionary<string, string>();
            msg.Add("CN", string.Format(message, args));
            msg.Add("EN", string.Format(message, args));
            var request = new Publish() { Header = XfwUtils.CreateHeader(headername, EAPServer) };
            request.Body.AddString(CItems.EqpID, eqpID);
            request.Body.AddString(CItems.MessageType, MessageType.Info.ToString());
            request.Body.AddObject(CItems.TerminalMessage, msg);
            request.Body.AddString(CItems.MessageOrigin, messageOrigin.ToString());

            var ctx = XfwContext.GetMqContextByEAP(EAPServer);
            var strText = XfwUtils.Serialization(request.GetSerializationObject());
            ctx.Publish(strText);
        }

        /// <summary>
        /// 人工针痕确认
        /// </summary>
        /// <param name="eqpID"></param>
        /// <param name="messageType"></param>
        /// <param name="message"></param>
        /// <param name="messageOrigin"></param>
        public void ConfrimNeedMarkResult(string eqpID, MessageType messageType, Dictionary<string, string> message, MessageOrigin messageOrigin)
        {
            if (string.IsNullOrEmpty(eqpID))
            {
                eqpID = Dict.Current.DaemonName;
            }
            var headername = "ShowConfrimNeedMarkResult";
            if (message == null || message.Count == 0)
            {
                CimLogger.Warning($"{Name}.ShowConfrimNeedMarkResult() Execute, message==null|| message.Count==0.");
                return;
            }
            string needletype = "0";
            if (Dict.Current.NeedleMaterial.Trim()== "合金针")//判断金针或铼钨针
            {
                needletype = "1";//金针
            }
            else
            {
                needletype ="0";//铼钨针
            }
            var request = new Publish() { Header = XfwUtils.CreateHeader(headername, EAPServer) };
            request.Body.AddString(CItems.EqpID, eqpID);
            request.Body.AddString(CItems.MessageType, messageType.ToString());
            request.Body.AddObject(CItems.TerminalMessage, message);
            request.Body.AddString(CItems.MessageOrigin, messageOrigin.ToString());
            request.Body.AddString(CItems.NeedleType, needletype);
            var ctx = XfwContext.GetMqContextByEAP(EAPServer);
            var strText = XfwUtils.Serialization(request.GetSerializationObject());
            ctx.Publish(strText);
        }
        /// <summary>
        /// 发送Lot状态
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void SendLotStatusRequest(XfwArgs xfwArgs)
        {
            try
            {
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                if (string.IsNullOrEmpty(eqpID))
                {
                    eqpID = Dict.Current.DaemonName;
                }
                var request = new Publish() { Header = XfwUtils.CreateHeader(SendLotStatus, EAPServer) };
                request.Body.AddString(CItems.EqpID, eqpID);
                request.Body.AddString(CItems.lotStatus, "RUNNING");

                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.SendLotStatusRequest() Execute Error.");
            }
        }

        /// <summary>
        /// 发送Wafer的测试状态
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void SendWaferStatusRequest(XfwArgs xfwArgs)
        {
            try
            {
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                var unitStatus = xfwArgs.Header[CItems.unitStatus]?.ToString();
                var position = xfwArgs.Header[CItems.position]?.ToString();
                var unitId = xfwArgs.Header[CItems.unitId]?.ToString();
                if (string.IsNullOrEmpty(eqpID))
                {
                    eqpID = Dict.Current.DaemonName;
                }
                var request = new Publish() { Header = XfwUtils.CreateHeader(SendLotStatus, EAPServer) };
                request.Body.AddString(CItems.EqpID, eqpID);

                request.Body.AddString(CItems.unitStatus, unitStatus);
                request.Body.AddString(CItems.unitStatus, position);
                request.Body.AddString(CItems.unitStatus, unitId);

                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.SendLotStatusRequest() Execute Error.");
            }
        }

        /// <summary>
        /// 暂停OffLine作业
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void StopProcess(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                Dict.Current.EAPRunMode = RunMode.ManualOperation;
                Dict.Current.CurState = "1";
                dbServer.InsertMsgInfo($"手动暂停OCR OffLine...", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);
                Dict.Current.lotInfo = new LotInfo();
            }
            catch (Exception ex)
            {
                xfwArgs.Header[CItems.ReturnCode] = "-1";
                CimLogger.Error(ex, $"{Name}.SendLotStatusRequest() Execute Error.");
            }
        }
        public void StopProcessReply(XfwArgs xfwArgs)
        {
            try
            {
                var returnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString();
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Return = new Return { ReturnCode = returnCode, ReturnMessage = returnCode };

                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
                dbServer.InsertMsgInfo($"手动暂停OCR OffLine 成功", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);

            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.StopProcessReply() Execute Error.");
            }
        }
        /// <summary>
        /// 开始OnLine作业
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void StartProcess(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                Dict.Current.EAPRunMode = RunMode.AutomaticOperation;
                dbServer.InsertMsgInfo($"手动 OCR OnLine作业...", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);

            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.StartProcess() Execute Error.");
            }
        }
        public void StartProcessReply(XfwArgs xfwArgs)
        {
            try
            {
                var returnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString();
                // var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Return = new Return { ReturnCode = returnCode, ReturnMessage = returnCode };
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
                dbServer.InsertMsgInfo($"手动 OCR OnLine作业成功", Dict.Current.lotInfo.eqptID, Dict.Current.lotInfo.lotId);

            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.StartProcessReply() Execute Error.");
            }
        }

        /// <summary>
        /// 选片
        /// </summary>
        /// <param name="xfwArgs"></param>
        public void SelectWaferID(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                xfwArgs.Header[CItems.EqpID] = eqpID;
                xfwArgs.Header[CItems.SelectWaferID] = body.GetVal(CItems.SelectWaferID);
                
                xfwArgs.Header[CItems.MesWaferID] = body.GetVal(CItems.MesWaferID);
                xfwArgs.Header[CItems.IsFullmeasurement] = body.GetVal(CItems.IsFullmeasurement);
                xfwArgs.Header[CItems.UnitidList] = body.GetVal(CItems.UnitidList);
                Dict.Current.lotInfo.LotLists = body.GetVal(CItems.SelectWaferID);
                //将已测试层数置为null
                Dict.Current.lotInfo.testSlot = null;
                string IsAll = body.GetVal("IsAll");
                //string waferids2 = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25";
                //Dict.Current.lotInfo.qty1 = "25";
                //if (Dict.Current.lotInfo.qty1 == "13")
                //{
                //    waferids2 = "1,2,3,4,5,6,7,8,9,10,11,12,13";
                //}
                //Dict.Current.lotInfo.LotLists = waferids2;
                //xfwArgs.Header[CItems.SelectWaferID] = waferids2;
                //if (!string.IsNullOrEmpty(IsAll) && IsAll == "Y")
                //{
                //    if (!string.IsNullOrEmpty(Dict.Current.NotParas))
                //    {
                //        string ProcessId = Dict.Current.lotInfo.ProcessId;
                //        CimLogger.Information($"{Name}.SelectWaferID() NotParas={Dict.Current.NotParas};SelectWaferID={Dict.Current.lotInfo.LotLists};ProcessId={ProcessId};");
                //        if (!string.IsNullOrEmpty(ProcessId) && ProcessId.Length > 4)
                //        {
                //            string proc = ProcessId.Substring(0, 4);
                //            //参数名称为ProcessID除了这些开头的批号外，其他批号没有选片信息时都就行全测，发空值                        
                //            if (Dict.Current.NotParas.Contains(proc))
                //            {
                //                string waferids = "";
                //                //string waferids = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25";
                //                //if (Dict.Current.lotInfo.qty1 == "13")
                //                //{
                //                //    waferids = "1,2,3,4,5,6,7,8,9,10,11,12,13";
                //                //}
                //                Dict.Current.lotInfo.LotLists = waferids;
                //                CimLogger.Information($"{Name}.SelectWaferID() 全测信息 waferids={waferids};");
                //            }
                //        }
                //    }
                //}
                CimLogger.Information($"{Name}.SelectWaferID() 全测信息 LotLists={Dict.Current.lotInfo.LotLists};");
                Dict.Current.lotInfo.MesWaferList = body.GetVal(CItems.MesWaferID);
                Dict.Current.lotInfo.IsFullmeasurement = body.GetVal(CItems.IsFullmeasurement);
                Dict.Current.lotInfo.NeedleMarkDetectionWaferIdList = body.GetVal(CItems.NeedleMarkDetectionWaferId);
                Dict.Current.lotInfo.UnitidList = body.GetVal(CItems.UnitidList);
                if (!string.IsNullOrEmpty(body.GetVal(CItems.TestMode))) {
                    Dict.Current.lotInfo.TestMode = body.GetVal(CItems.TestMode);
                }
                //下发作业时将当前批次加入到出站队列中
                Dict.Current.lotInfo.lotState = CItems.InProcessing;
           
                xfwArgs.Header[CItems.ReturnCode] = "0";
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SelectWaferID() Execute Error.");
            }
        }


        public void SendWaferEndRequest(XfwArgs xfwArgs)
        {
            try
            {
                STDF stdf = xfwArgs.Header[CItems.STDF] as STDF;
                var waferId = stdf.waferId;
                var passNo = stdf.passNo;
                var startTime = stdf.startTime;
                var finishTime = stdf.finishTime;
                var lotId = stdf.lotId;
                var eqpID = xfwArgs.Header[CItems.EqpID]?.ToString();
                var request = new Publish() { Header = XfwUtils.CreateHeader("SendWaferEnd", EAPServer) };
                request.Body.AddString(CItems.waferId, waferId);
                request.Body.AddString(CItems.passDieCount, passNo);
                request.Body.AddString(CItems.EqpID, eqpID);
                var ctx = XfwContext.GetMqContextByEAP(EAPServer);
                var strText = XfwUtils.Serialization(request.GetSerializationObject());
                ctx.Publish(strText);
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex, $"{Name}.SendLotStatusRequest() Execute Error.");
            }
        }
        public void SelectWaferIDReply(XfwArgs xfwArgs)
        {
            try
            {
                var returnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString();
                // var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Return = new Return { ReturnCode = returnCode, ReturnMessage = returnCode };
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SelectWaferIDReply() Execute Error.");
            }
        }
        public void SelectNeedleMarkDetectionWaferId(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                var eqpID = body.GetVal(CItems.EqpID);
                xfwArgs.Header[CItems.EqpID] = eqpID;
                xfwArgs.Header[CItems.NeedleMarkDetectionWaferId] = body.GetVal(CItems.NeedleMarkDetectionWaferId);
                Dict.Current.lotInfo.NeedleMarkDetectionWaferIdList = body.GetVal(CItems.NeedleMarkDetectionWaferId);
                xfwArgs.Header[CItems.ReturnCode] = "0";
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SlectNeedleMarkDetectionWaferId() Execute Error.");
            }
        }
        public void SelectNeedleMarkDetectionWaferIdReply(XfwArgs xfwArgs)
        {
            try
            {
                var returnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString();          
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Return = new Return { ReturnCode = returnCode, ReturnMessage = returnCode };
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.SelectWaferIDReply() Execute Error.");
            }
        }

        public void ClearAlarm(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                xfwArgs.Header[CItems.AlarmID] = body.GetVal(CItems.AlarmID);
                Dict.Current.AlarmID = body.GetVal(CItems.AlarmID);
                xfwArgs.Header[CItems.ReturnCode] = "0";
                CimLogger.Information("AlarmID"+ Dict.Current.AlarmID);
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.ClearAlarm() Execute Error.");
            }
        }

        public void ClearAlarmReply(XfwArgs xfwArgs)
        {
            try
            {
                var returnCode = xfwArgs.Header[CItems.ReturnCode]?.ToString();
                // var json = XfwUtils.DeserializeObject<JObject>(body);
                var obj = xfwArgs.NATSData.Data;
                var res = new Response { Header = obj.GetHeaderObject() };
                res.Header.EventTime = DateTime.Now.ToString(CItems.DateTimeFormat);
                res.Header.MachineName = XfwContext.ServerName;
                res.Return = new Return { ReturnCode = returnCode, ReturnMessage = returnCode };
                xfwArgs.NATSData.ReplyData = res.GetSerializationObject();
                XfwContext.XfwAgent.Reply(xfwArgs.NATSData.Context, xfwArgs.NATSData);
                xfwArgs.SetReturnCodeOK();
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.ClearAlarmReply() Execute Error.");
            }
        }

        public void SendNeedMardUserInfo(XfwArgs xfwArgs)
        {
            try
            {
                var obj = xfwArgs.NATSData.Data;
                var body = obj.GetBody();
                xfwArgs.Header[CItems.UserName] = body.GetVal(CItems.UserName);
                Dict.Current.NeedMardUseId = body.GetVal(CItems.UserName);
                Dict.Current.NeedMardResult = body.GetVal(CItems.NeedleTypeMessage);
                Dict.Current.NeedleTypeMessageRemark = body.GetVal(CItems.NeedleTypeMessageRemark);
                xfwArgs.Header[CItems.ReturnCode] = "0";
                xfwArgs.SetReturnCodeOK();
                CimLogger.Information("NeedMardUseId:" + Dict.Current.NeedMardUseId +";"+ "NeedMardResult:" + Dict.Current.NeedMardResult+";"+ "NeedMardCoordinate:"+ Dict.Current.NeedMardCoordinate);
                var rptRunHisTemps = dbServer.InsertMsgTo_NeedMardMessage( Dict.Current.lotInfo.lotId,DateTime.Now, Dict.Current.NeedMardResult, Dict.Current.NeedMardUseId, Dict.Current.NeedleTypeMessageRemark, Dict.Current.NeedMardCoordinate);           
            }
            catch (Exception ex)
            {
                xfwArgs.SetReturnCodeNG(ex.Message);
                CimLogger.Error(ex, $"{Name}.ClearAlarm() Execute Error.");
            }
        }

    }
}
